package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.dto.ActivityDto;
import com.zhentao.dto.CartDto;
import com.zhentao.pojo.*;
import com.zhentao.service.*;
import com.zhentao.vo.Result;
import com.zhentao.vo.ShoppingCartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private CategoryLevel1Service categoryLevel1Service;
    @Autowired
    private CategoryLevel2Service categoryLevel2Service;
    @Autowired
    private ProductService productService;
    @Autowired
    private SpecGroupService specGroupService;
    @Autowired
    private ProductParameterService productParameterService;
    @Autowired
    private MarketingProductService marketingProductService;

    // 1.1获取一级分类
    @RequestMapping("/getCategoryLevel1")
    public List<CategoryLevel1> getCategoryLevel1() {
        return categoryLevel1Service.list(new QueryWrapper<CategoryLevel1>().orderByAsc("sort_order"));
    }

    // 1.2根据level1Id获取二级分类
    @RequestMapping("/getCategoryLevel2")
    public List<CategoryLevel2> getCategoryLevel2(Integer level1Id) {
        return categoryLevel2Service.list(new QueryWrapper<CategoryLevel2>().eq("level1_id", level1Id).orderByAsc("sort_order"));
    }

    // 1.3获取推荐商品分类
    @RequestMapping("/getRecommendProduct")
    public List<CategoryLevel2> getRecommendProduct() {
        return categoryLevel2Service.getRecommendProduct();
    }

    // 1.4获取推荐商品
    @RequestMapping("/getProduct")
    public List<Product> getProduct(){
        return productService.getRecommendProduct();
    }

    // 1.5获取商品活动
    @RequestMapping("/getProductActivity")
    public List<ActivityDto> getProductActivity(){
        return marketingProductService.getProductActivity();
    }

    // 2.1查询商品列表
    @RequestMapping("/getProductList")
    public Page<Product> getProductList( Integer pageNum, Integer pageSize, Integer level2Id, Integer sort){
        return productService.getProductList(level2Id, sort, pageNum, pageSize);
    }

    // 2.2查询商品详情
    @RequestMapping("/getProductDetail")
    public Product getProductDetail(Integer productId){
        return productService.getProductDetail(productId);
    }

    // 2.3获取商品规格
    @RequestMapping("/getProductSpecs")
    public List<SpecGroup> getProductSpecs(Integer productId){
        return specGroupService.getProductSpecs(productId);
    }

    // 2.4获取商品参数
    @RequestMapping("/getProductParam")
    public List<ProductParameter> getProductParam(Integer productId){
        return productParameterService.getProductParam(productId);
    }

    // 3.1获取某类推荐商品
    @RequestMapping("/getRecommendProducts")
    public List<Product> getRecommendProducts(Integer level2Id){
        return productService.getRecommendProducts(level2Id);
    }

    @Autowired
    private AfterSaleTypeService afterSaleTypeService;
    // 4.1 获取售后保障
    @RequestMapping("/getAfterSale")
    public List<AfterSaleType> getAfterSale(){
        return afterSaleTypeService.list();
    }

    @Autowired
    private ProductReviewService productReviewService;

    // 5.1 查询商品评价
    @RequestMapping("/getProductEvaluation")
    public Page<ProductReview> getProductEvaluation(Integer productId, Integer pageNum, Integer pageSize, Integer sort){
        return productReviewService.getProductEvaluation(productId, pageNum, pageSize, sort);
    }

    @Autowired
    private UserFavoritesService userFavoritesService;

    // 5.2 用户收藏商品
    @RequestMapping("/addProductCollection")
    public void addProductCollection(UserFavorites favorite){
        favorite.setCreatedAt(new Date());
        userFavoritesService.save(favorite);
    }
    // 5.3 取消收藏商品
    @RequestMapping("/cancelProductCollection")
    public void cancelProductCollection(UserFavorites favorite){
        userFavoritesService.remove(new QueryWrapper<UserFavorites>()
                .eq("product_id", favorite.getProductId())
                .eq("user_id", favorite.getUserId())
        );
    }
    // 5.4 获取用户收藏商品(判断收藏状态）
    @RequestMapping("/getProductCollection")
    public UserFavorites getProductCollection(UserFavorites favorite){
        return userFavoritesService.getOne(new QueryWrapper<UserFavorites>()
                .eq("product_id", favorite.getProductId())
                .eq("user_id", favorite.getUserId())
        );
    }

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private ShoppingCartItemService shoppingCartItemService;
    // 6.1 添加购物车
    @RequestMapping("/addProductToCart")
    @Transactional(rollbackFor = Exception.class)
    public Result addProductToCart(@RequestBody ShoppingCartVo shoppingCart){
        try {
            // 参数验证
            if (shoppingCart == null || shoppingCart.getUserId() == null || 
                shoppingCart.getProductId() == null || shoppingCart.getQuantity() == null || 
                shoppingCart.getQuantity() <= 0) {
                return Result.fail("请求参数不完整或无效");
            }
            
            // 验证商品是否存在
            Product product = productService.getById(shoppingCart.getProductId());
            if (product == null) {
                return Result.fail("商品不存在");
            }
            
            // 检查库存（如果有库存字段）
             if (product.getStock() != null && product.getStock() < shoppingCart.getQuantity()) {
                 return Result.fail("库存不足");
             }
            
            // 查找或创建购物车
            QueryWrapper<ShoppingCart> cartQuery = new QueryWrapper<>();
            cartQuery.eq("user_id", shoppingCart.getUserId())
                    .eq("cart_type", shoppingCart.getCartType());
            if (shoppingCart.getCartType() == 2 && shoppingCart.getShipId() != null) {
                cartQuery.eq("ship_id", shoppingCart.getShipId());
            }
            
            ShoppingCart cart = shoppingCartService.getOne(cartQuery);
            if (cart == null) {
                // 创建新购物车
                cart = new ShoppingCart();
                cart.setUserId(shoppingCart.getUserId());
                cart.setCartType(shoppingCart.getCartType());
                if (shoppingCart.getCartType() == 2) {
                    cart.setShipId(shoppingCart.getShipId());
                }
                cart.setCreateTime(new Date());
                boolean saveResult = shoppingCartService.save(cart);
                if (!saveResult) {
                    return Result.fail("创建购物车失败");
                }
            }
            
            // 检查是否已存在相同商品和规格的购物车项
            QueryWrapper<ShoppingCartItem> itemQuery = new QueryWrapper<>();
            itemQuery.eq("cart_id", cart.getCartId())
                    .eq("product_id", shoppingCart.getProductId())
                    .eq("is_deleted", 0);
            
            // 处理规格值查询条件
            String specValue = shoppingCart.getSpecValue();
            if (specValue != null && !specValue.trim().isEmpty()) {
                itemQuery.eq("spec_value_id", specValue.trim());
            } else {
                // 查询spec_value_id为null或空字符串的记录
                itemQuery.and(wrapper -> wrapper.isNull("spec_value_id").or().eq("spec_value_id", ""));
            }
            
            ShoppingCartItem existingItem = shoppingCartItemService.getOne(itemQuery);
            if (existingItem != null) {
                // 更新数量
                existingItem.setQuantity(existingItem.getQuantity() + shoppingCart.getQuantity());
                existingItem.setUpdateTime(new Date());
                boolean updateResult = shoppingCartItemService.updateById(existingItem);
                if (!updateResult) {
                    return Result.fail("更新购物车商品数量失败");
                }
            } else {
                // 添加新的购物车项 - 使用同步锁防止并发插入
                synchronized (this) {
                    // 再次检查是否存在，防止并发情况下的重复插入
                    ShoppingCartItem doubleCheckItem = shoppingCartItemService.getOne(itemQuery);
                    if (doubleCheckItem != null) {
                        // 如果在锁内再次发现存在，则更新数量
                        doubleCheckItem.setQuantity(doubleCheckItem.getQuantity() + shoppingCart.getQuantity());
                        doubleCheckItem.setUpdateTime(new Date());
                        boolean updateResult = shoppingCartItemService.updateById(doubleCheckItem);
                        if (!updateResult) {
                            return Result.fail("更新购物车商品数量失败");
                        }
                    } else {
                        // 确实不存在，执行插入
                        ShoppingCartItem cartItem = new ShoppingCartItem();
                        cartItem.setCartId(cart.getCartId());
                        cartItem.setProductId(shoppingCart.getProductId());
                        cartItem.setSpecValueId(specValue != null && !specValue.trim().isEmpty() ? specValue.trim() : null);
                        cartItem.setQuantity(shoppingCart.getQuantity());
                        cartItem.setCreateTime(new Date());
                        cartItem.setIsDeleted(0);
                        try {
                            boolean itemSaveResult = shoppingCartItemService.save(cartItem);
                            if (!itemSaveResult) {
                                return Result.fail("添加购物车商品失败");
                            }
                        } catch (Exception saveException) {
                            // 如果插入失败（可能是唯一键冲突），尝试查找并更新
                            if (saveException.getMessage().contains("Duplicate entry") || saveException.getMessage().contains("uk_cart_product_spec")) {
                                ShoppingCartItem conflictItem = shoppingCartItemService.getOne(itemQuery);
                                if (conflictItem != null) {
                                    conflictItem.setQuantity(conflictItem.getQuantity() + shoppingCart.getQuantity());
                                    conflictItem.setUpdateTime(new Date());
                                    boolean updateResult = shoppingCartItemService.updateById(conflictItem);
                                    if (!updateResult) {
                                        return Result.fail("更新购物车商品数量失败");
                                    }
                                } else {
                                    throw saveException; // 重新抛出异常
                                }
                            } else {
                                throw saveException; // 重新抛出异常
                            }
                        }
                    }
                }
            }
            
            return Result.success("添加购物车成功");
            
        } catch (Exception e) {
            // 记录异常日志
            // log.error("添加购物车异常", e);
            return Result.fail("添加购物车失败：" + e.getMessage());
        }
    }
    @Autowired
    private ShipCompanyService shipCompanyService;
    @Autowired
    private ShipService shipService;
    // 6.2 获取可选船舶
    @RequestMapping("/getShipList")
    public List<ShipCompany> getShipList(){
        List<ShipCompany> list = shipCompanyService.list();
        if (list == null || list.isEmpty()) {
            return list;
        }

        // 提取所有船舶公司ID
        List<Long> companyIds = list.stream()
                .map(ShipCompany::getCompanyId)
                .collect(Collectors.toList());

        // 一次性查询所有相关船舶
        List<Ship> allShips = shipService.list(new QueryWrapper<Ship>()
                .in("company_id", companyIds)
                .eq("status", 1));

        // 按公司ID分组船舶
        Map<Long, List<Ship>> shipsByCompany = allShips.stream()
                .collect(Collectors.groupingBy(Ship::getCompanyId));

        // 设置每个船舶公司的船舶列表
        for (ShipCompany shipCompany : list) {
            List<Ship> companyShips = shipsByCompany.getOrDefault(shipCompany.getCompanyId(), new ArrayList<>());
            shipCompany.setShips(companyShips);
        }

        return list;
    }
    @Autowired
    private SpecValueService specValueService;
    @Autowired
    private ProductImageService productImageService;

    // 6.3 获取购物车列表
    @RequestMapping("/getCartList")
    public List<CartDto> getCartList(Long userId, Integer cartType){
        List<ShoppingCart> cartList = shoppingCartService.list(new QueryWrapper<ShoppingCart>()
                .eq("user_id", userId)
                .eq("cart_type", cartType));
        if (cartList == null || cartList.isEmpty()) {
            return new ArrayList<>();
        }
        List<ShoppingCartItem> cartItemList = shoppingCartItemService.list(new QueryWrapper<ShoppingCartItem>()
                .in("cart_id", cartList.stream().map(ShoppingCart::getCartId).collect(Collectors.toList()))
                .eq("is_deleted", 0));
        if (cartItemList == null || cartItemList.isEmpty()) {
            return new ArrayList<>();
        }
        // 批量获取所有商品信息
        List<Long> productIds = cartItemList.stream().map(ShoppingCartItem::getProductId).collect(Collectors.toList());
        List<Product> products = productService.listByIds(productIds);
        Map<Long, Product> productMap = products.stream().collect(Collectors.toMap(Product::getProductId, p -> p));

        // 批量获取产品图片
        List<ProductImage> productImages = productImageService.list(new QueryWrapper<ProductImage>()
                .in("product_id", productIds)
                .eq("type", 0)
                .eq("sort_order", 1));
        Map<Long, String> productImageMap = productImages.stream().collect(Collectors.toMap(ProductImage::getProductId, ProductImage::getImageUrl));

        List<CartDto> cartDtoList = new ArrayList<>();
        for (ShoppingCartItem cartItem : cartItemList) {
            CartDto cartDto = new CartDto();
            cartDto.setOrderId(cartItem.getItemId());
            cartDto.setProductId(cartItem.getProductId());
            cartDto.setSpecValueId(cartItem.getSpecValueId()); // 返回原始规格ID供下单使用
            cartDto.setQuantity(cartItem.getQuantity());
            // 获取该规格售价
            String[] specValueIds = cartItem.getSpecValueId() != null ? cartItem.getSpecValueId().split(",") : new String[0];
            List<SpecValue> specValues = specValueIds.length > 0 ?
                    specValueService.listByIds(Arrays.asList(specValueIds)) : new ArrayList<>();

            // 增加null检查防止空指针异常
            if (specValues == null) {
                specValues = new ArrayList<>();
            }

            // 使用String.join优化字符串拼接
            String name = specValues.stream()
                    .map(SpecValue::getName)
                    .collect(Collectors.joining());
            cartDto.setSpecValue(name);

            // 获取specValues里面的priceDiff之和
            BigDecimal sum = specValues.stream()
                    .filter(sv -> sv.getPriceDiff() != null)  // 增加null检查
                    .map(SpecValue::getPriceDiff)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);

            // 获取商品售价
            Product product = productMap.get(cartItem.getProductId());
            if (product != null && product.getPrice() != null) {
                cartDto.setTotalPrice(product.getPrice().add(sum).doubleValue());
                cartDto.setProductName(product.getName());
                String imageUrl = productImageMap.get(cartItem.getProductId());
                if (imageUrl != null) {
                    cartDto.setPic(imageUrl);
                }
            } else {
                cartDto.setTotalPrice(sum.doubleValue());
            }
            cartDtoList.add(cartDto);
        }
        return cartDtoList;
    }

    // 6.4.2 批量删除购物车商品
    @RequestMapping("/deleteCartItems")
    public Result deleteCartItems(@RequestBody List<Integer> itemIds, Long userId){
        try {
            if (itemIds == null || itemIds.isEmpty()) {
                return Result.fail("请选择要删除的购物车项");
            }

            // 验证所有购物车项是否都属于该用户
            List<ShoppingCartItem> items = shoppingCartItemService.listByIds(itemIds);
            if (items.size() != itemIds.size()) {
                return Result.fail("部分购物车项不存在");
            }

            // 检查用户权限
            List<Long> cartIds = items.stream().map(ShoppingCartItem::getCartId).collect(Collectors.toList());
            List<ShoppingCart> carts = shoppingCartService.listByIds(cartIds);
            Map<Long, ShoppingCart> cartMap = carts.stream().collect(Collectors.toMap(ShoppingCart::getCartId, c -> c));

            for (ShoppingCartItem item : items) {
                ShoppingCart cart = cartMap.get(item.getCartId());
                if (cart == null || !cart.getUserId().equals(userId)) {
                    return Result.fail("无权限删除购物车项: " + item.getItemId());
                }
            }

            boolean result = shoppingCartItemService.removeBatchByIds(itemIds);
            return result ? Result.success() : Result.fail("批量删除失败");
        } catch (Exception e) {
            return Result.fail("批量删除过程中发生错误: " + e.getMessage());
        }
    }

    // 6.5 修改购物车商品数量
    @RequestMapping("/updateCartItem")
    public Result updateCartItem(Integer itemId, Integer quantity) {
        // 参数校验
        if (itemId == null || quantity == null) {
            return Result.fail("参数错误");
        }

        if (quantity <= 0) {
            return Result.fail("商品数量必须大于0");
        }

        try {
            // 执行更新操作，同时更新更新时间
            boolean result = shoppingCartItemService.update(
                    new UpdateWrapper<ShoppingCartItem>()
                            .eq("item_id", itemId)
                            .set("quantity", quantity)
                            .set("update_time", new Date())
            );

            if (result) {
                return Result.success();
            } else {
                return Result.fail("更新失败，未找到对应的购物车项");
            }
        } catch (Exception e) {
            return Result.fail("更新过程中发生错误: " + e.getMessage());
        }
    }


    //3.3 商品模块
    //3.3.1 商品详情页

    // 查询所有商品

    //基本信息:商品轮播图、名称、售价、库存状态

    //营销活动:秒杀、团购、购物节等活动标签展示

    //规格选择:支持多规格商品的数量和规格组合选择

    //评价体系:显示最近 3条评价，支持查看全部评价

    //详细信息:图文详情、商品参数、售后保障说明

    //相关推荐:展示同类型或互补商品推荐列表

    //3.3.2 购物车管理
    //双购物车体系:船舶购物车与个人购物车独立管理

    //商品操作:编辑数量、删除商品、跨购物车移动

    //结算功能:统计选中商品总价，支持去结算跳转

    //下架标识:已下架商品在购物车中显示特殊标记

    //3.3.3 订单管理
    //订单确认页(船舶):

    //收货信息:默认目的港，支持修改;船长姓名、联系方式

    //商品详情:展示订购商品详情及价格.

    //费用计算:商品总计、运费(按港口和货物类型计算)

    //支付方式:账单/公司支付、现金支付

    //订单确认页(个人):

    //运费方案:跟随船舶免运费或个人订单分摊运费

    //支付方式:在线支付、现金支付(需海员认证)

    //订单状态:待付款、配货中、送货中、已完成

    //异常订单:因目的港变更生成，自动重新计算运费和价格

}
